// 引入工具类和API
const app = getApp()
const api = require('../../utils/api')
const util = require('../../utils/util.js')

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  })
  canvas.setChart(chart)

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const systolic = params[0]
        const diastolic = params[1]
        return `${systolic.name}<br/>
                收缩压: ${systolic.value} mmHg<br/>
                舒张压: ${diastolic.value} mmHg<br/>
                状态: ${systolic.value >= 140 || diastolic.value >= 90 ? '偏高' : 
                      systolic.value < 90 || diastolic.value < 60 ? '偏低' : '正常'}`
      }
    },
    legend: {
      data: ['收缩压', '舒张压'],
      top: 0
    },
    grid: {
      top: 50,
      bottom: 30,
      left: 40,
      right: 20
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
      axisLine: { lineStyle: { color: '#999' } }
    },
    yAxis: {
      type: 'value',
      splitLine: { lineStyle: { color: '#eee' } },
      axisLine: { lineStyle: { color: '#999' } },
      axisLabel: {
        formatter: '{value} mmHg'
      }
    },
    series: [{
      name: '收缩压',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: { color: '#ff4d4f' },
      markArea: {
        silent: true,
        data: [[{
          yAxis: 90,
          itemStyle: { color: 'rgba(255, 77, 79, 0.05)' }
        }, {
          yAxis: 140
        }]]
      }
    }, {
      name: '舒张压',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: { color: '#1aad19' },
      markArea: {
        silent: true,
        data: [[{
          yAxis: 60,
          itemStyle: { color: 'rgba(26, 173, 25, 0.05)' }
        }, {
          yAxis: 90
        }]]
      }
    }]
  }

  chart.setOption(option)
  return chart
}

Page({
  data: {
    timeRange: 'day', // day, week, month
    showDayView: true,
    showWeekView: false,
    showMonthView: false,
    currentDate: '',
    today: '',           // YYYY-MM-DD 格式
    selectedDateStr: '', // YYYY-MM-DD 格式
    selectedDate: null,  // 存储选中的日期对象
    qualityLevel: '--',
    qualityClass: '',
    todayRecords: [],
    systolicData: [],
    diastolicData: [],
    xLabels: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
    statistics: {
      averageSystolic: '--',
      averageDiastolic: '--',
      maxSystolic: '--',
      maxDiastolic: '--',
      minSystolic: '--',
      minDiastolic: '--'
    },
    ec: {
      lazyLoad: true,
      disableTouch: false
    },
    weekEc: {
      lazyLoad: true,
      disableTouch: false,
      onInit: initChart
    },
    monthEc: {
      lazyLoad: true,
      disableTouch: false,
      onInit: initChart
    },
    lastFetchTime: null,
    needRefresh: true,
    cachedData: {
      day: {},
      week: {},
      month: {}
    },
    useSimpleChart: true,
    systolicTarget: 120,
    diastolicTarget: 80
  },

  onLoad: function (options) {
    // 获取用户的血压目标设置
    const settings = wx.getStorageSync('bloodPressureSettings') || {};
    this.setData({
      systolicTarget: settings.targetSystolic || 120,
      diastolicTarget: settings.targetDiastolic || 80,
      useSimpleChart: true,
      needRefresh: false // 默认不需要刷新数据
    });

    this.initDates()
  },

  onShow() {
    console.log('bloodPressureDetail onShow')
    
    // 初始化日期（如果需要）
    if (!this.data.selectedDateStr) {
      this.initDates()
    }
    
    // 设置强制刷新标志
    wx.setStorageSync('blood_pressure_detail_needs_refresh', true);
    
    // 强制刷新机制 - 每次显示页面时都强制刷新数据
    this.setData({ 
      needRefresh: true,
      lastFetchTime: null 
    });
    this.clearAllCache();
    
    // 立即刷新数据 
      this.fetchData();
  },

  initDates() {
    const now = new Date()
    const today = now.toISOString().split('T')[0]  // YYYY-MM-DD 格式
    const currentDate = this.formatDateToString(now)
    
    this.setData({
      today,
      selectedDateStr: today,
      currentDate,
      selectedDate: now
    })
  },

  formatDateToString(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}年${month}月${day}日`
  },

  onSelectDate(e) {
    const date = e.detail.value
    const selectedDate = new Date(date)
    const currentDate = this.formatDateToString(selectedDate)
    
    // 如果选择了不同的日期，需要刷新数据
    const needRefresh = date !== this.data.selectedDateStr
    
    this.setData({
      currentDate,
      selectedDateStr: date,
      selectedDate,
      needRefresh
    }, () => {
      // 只有需要刷新时才获取数据
      if (needRefresh) {
        this.fetchData()
      }
    })
  },

  async fetchData() {
    try {
      const { timeRange, selectedDateStr } = this.data
      // 检查缓存
      const cacheKey = `${timeRange}_${selectedDateStr}`
      if (this.data.cachedData[timeRange][cacheKey]) {
        // 使用缓存数据
        const cachedData = this.data.cachedData[timeRange][cacheKey]
        console.log('使用缓存的血压数据:', cachedData)
        this.updateViewWithData(timeRange, cachedData)
        return
      }

      const startDate = new Date(selectedDateStr)
      startDate.setHours(0, 0, 0, 0)
      
      let endDate = new Date(startDate)
      // 根据时间范围设置不同的日期范围
      switch(timeRange) {
        case 'week':
          // 获取本周的数据
          startDate.setDate(startDate.getDate() - startDate.getDay()) // 设置为本周日
          endDate = new Date(startDate)
          endDate.setDate(startDate.getDate() + 7)
          break
        case 'month':
          // 获取本月的数据
          startDate.setDate(1) // 设置为本月第一天
          endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 1)
          break
        default: // day
          endDate.setDate(startDate.getDate() + 1)
          break
      }

      console.log('正在获取血压数据, 时间范围:', timeRange, '开始日期:', startDate.toISOString(), '结束日期:', endDate.toISOString())

      const records = await api.health.getRecords({ 
        type: 'bloodPressure',  // 使用驼峰命名，与storage中定义的键一致
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString()
      })

      console.log('获取到的血压记录:', records, '记录数量:', records ? records.length : 0)

      // 缓存数据
      this.setData({
        [`cachedData.${timeRange}.${cacheKey}`]: records,
        lastFetchTime: Date.now() // 记录最后获取数据的时间戳
      })

      // 更新视图
      this.updateViewWithData(timeRange, records)
      
      return Promise.resolve()

    } catch (err) {
      console.error('获取记录失败:', err.message || err)
      wx.showToast({
        title: '暂无数据',
        icon: 'none'
      })
      return Promise.reject(err)
    }
  },

  updateViewWithData(timeRange, records) {
    switch(timeRange) {
      case 'day':
        if (records && records.length > 0) {
          console.log('开始处理日视图数据，记录数量:', records.length);
          
          // 按时间排序，确保最新的在前面
          records.sort((a, b) => {
            const dateA = new Date(a.measuredAt || a.timestamp);
            const dateB = new Date(b.measuredAt || b.timestamp);
            return dateB - dateA;
          });
          
          // 更新日视图数据
      this.setData({
            showDayView: true,
            showWeekView: false,
            showMonthView: false,
            dayRecords: records.map(record => {
              const date = new Date(record.measuredAt || record.timestamp);
              const timeString = `${this.formatNumber(date.getHours())}:${this.formatNumber(date.getMinutes())}`;
              
              return {
                ...record,
                timeString,
                systolicLevel: this.getBPLevel(record.systolic, 'systolic'),
                diastolicLevel: this.getBPLevel(record.diastolic, 'diastolic')
              };
            }),
            todayRecords: records.map(record => {
              const date = new Date(record.measuredAt || record.timestamp);
              return {
                ...record,
                timeStr: `${this.formatNumber(date.getHours())}:${this.formatNumber(date.getMinutes())}`
              };
            }),
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
        } else {
          this.setData({
            showDayView: true,
            showWeekView: false,
            showMonthView: false,
            dayRecords: [],
        todayRecords: [],
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
        }
        break;
      case 'week':
        if (records && records.length > 0) {
          console.log('开始处理周视图数据，记录数量:', records.length);
          const processedData = this.processWeeklyData(records);
          const { systolicData, diastolicData, xLabels, statistics } = processedData;
          
          // 准备图表数据 - 确保数据是数值
          const chartData = [
            {
              name: '收缩压',
              data: systolicData.map(val => val === null ? null : Number(val)),
              color: '#4CAF50'
            },
            {
              name: '舒张压',
              data: diastolicData.map(val => val === null ? null : Number(val)),
              color: '#ff9f43'
            }
          ];
          
          // 更新周视图数据
    this.setData({
            showWeekView: true,
            showDayView: false,
            showMonthView: false,
            systolicData,
            diastolicData,
            xLabels,
            chartData,
            statistics,
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
          
          console.log('周视图数据已更新:', {
            chartData,
            statistics
          });
        } else {
          this.setData({
            showWeekView: true,
            showDayView: false,
            showMonthView: false,
            chartData: [
              { name: '收缩压', data: Array(7).fill(null), color: '#4CAF50' },
              { name: '舒张压', data: Array(7).fill(null), color: '#ff9f43' }
            ],
            statistics: {
              average: '--/--',
              max: '--/--',
              min: '--/--',
              totalChange: '--'
            },
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
        }
        break;
      case 'month':
        if (records && records.length > 0) {
          console.log('开始处理月视图数据，记录数量:', records.length);
          
          // 按照日期排序记录
          records.sort((a, b) => {
            const dateA = new Date(a.measuredAt || a.timestamp);
            const dateB = new Date(b.measuredAt || b.timestamp);
            return dateA - dateB;
          });
          
          // 提取月份信息
          const selectedDate = new Date(this.data.selectedDateStr);
          const year = selectedDate.getFullYear();
          const month = selectedDate.getMonth();
          
          // 过滤出当月记录
          const monthRecords = records.filter(record => {
            const recordDate = new Date(record.measuredAt || record.timestamp);
            return recordDate.getFullYear() === year && recordDate.getMonth() === month;
          });
          
          // 提取血压数值和标签
          const systolicData = [];
          const diastolicData = [];
          const xLabels = [];
          
          // 处理每一条记录
          monthRecords.forEach(record => {
            const recordDate = new Date(record.measuredAt || record.timestamp);
            
            systolicData.push(parseInt(record.systolic, 10));
            diastolicData.push(parseInt(record.diastolic, 10));
            
            // 创建标签：日期+时间
            const day = recordDate.getDate();
            const hours = this.formatNumber(recordDate.getHours());
            const minutes = this.formatNumber(recordDate.getMinutes());
            xLabels.push(`${day}日 ${hours}:${minutes}`);
          });
          
          console.log('月视图处理后的数据点数量:', systolicData.length);
          
          // 如果没有记录但在当月，创建默认标签框架
          if (systolicData.length === 0) {
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            for (let i = 1; i <= daysInMonth; i += 5) { // 每5天一个标记点
              xLabels.push(`${i}日`);
            }
          }
          
          // 准备图表数据
          const chartData = [
            {
              name: '收缩压',
              data: systolicData,
              color: '#4CAF50'
            },
            {
              name: '舒张压',
              data: diastolicData,
              color: '#ff9f43'
            }
          ];
          
          // 计算统计值
          let statistics = {
            average: '--/--',
            max: '--/--',
            min: '--/--',
            totalChange: '--'
          };
          
          if (systolicData.length > 0 && diastolicData.length > 0) {
            const avgSystolic = Math.round(systolicData.reduce((a, b) => a + b, 0) / systolicData.length);
            const avgDiastolic = Math.round(diastolicData.reduce((a, b) => a + b, 0) / diastolicData.length);
            
            const maxSystolic = Math.max(...systolicData);
            const maxDiastolic = Math.max(...diastolicData);
            
            const minSystolic = Math.min(...systolicData);
            const minDiastolic = Math.min(...diastolicData);
            
            // 计算变化 - 比较第一个和最后一个测量值
            let totalChange = '--';
            if (systolicData.length >= 2) {
              totalChange = systolicData[systolicData.length - 1] - systolicData[0];
            }
            
            statistics = {
              average: `${avgSystolic}/${avgDiastolic}`,
              max: `${maxSystolic}/${maxDiastolic}`,
              min: `${minSystolic}/${minDiastolic}`,
              totalChange: totalChange
            };
          }
          
          console.log('月视图数据处理完成:', {
            chartData,
            statistics 
          });
          
          // 更新月视图数据
    this.setData({
            showMonthView: true,
            showDayView: false,
            showWeekView: false,
      systolicData,
      diastolicData,
      xLabels,
            chartData,
            statistics,
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
        } else {
          this.setData({
            showMonthView: true,
            showDayView: false,
            showWeekView: false,
            chartData: [
              { name: '收缩压', data: Array(30).fill(null), color: '#4CAF50' },
              { name: '舒张压', data: Array(30).fill(null), color: '#ff9f43' }
            ],
            statistics: {
              average: '--/--',
              max: '--/--',
              min: '--/--',
              totalChange: '--'
            },
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
        }
        break;
    }
  },

  initWeekChart() {
    this.weekChart = this.selectComponent('#weekChart')
    if (this.weekChart) {
      this.weekChart.init((canvas, width, height, dpr) => {
        const chart = initChart(canvas, width, height, dpr)
        
        // 更新图表数据
        const option = {
          xAxis: {
            data: this.data.xLabels
          },
          series: [{
            data: this.data.systolicData
          }, {
            data: this.data.diastolicData
          }]
        }

        chart.setOption(option)
        return chart
      })
    }
  },

  initMonthChart() {
    this.monthChart = this.selectComponent('#monthChart')
    if (this.monthChart) {
      this.monthChart.init((canvas, width, height, dpr) => {
        const chart = initChart(canvas, width, height, dpr)
        
        // 更新图表数据
        const option = {
          xAxis: {
            data: this.data.xLabels
          },
          series: [{
            data: this.data.systolicData
          }, {
            data: this.data.diastolicData
          }]
        }

        chart.setOption(option)
        return chart
      })
    }
  },

  evaluateBloodPressureQuality(records) {
    if (!records || records.length === 0) {
      return { 
        level: '--',
        class: ''
      }
    }
    
    // 计算平均血压
    const totalSystolic = records.reduce((sum, record) => sum + record.systolic, 0)
    const totalDiastolic = records.reduce((sum, record) => sum + record.diastolic, 0)
    const avgSystolic = totalSystolic / records.length
    const avgDiastolic = totalDiastolic / records.length
    
    // 血压质量评估
    if (avgSystolic >= 140 || avgDiastolic >= 90) {
      return {
        level: '偏高',
        class: 'quality-high'
      }
    } else if (avgSystolic < 90 || avgDiastolic < 60) {
      return {
        level: '偏低',
        class: 'quality-low'
      }
    } else {
      return {
        level: '正常',
        class: 'quality-normal'
      }
    }
  },

  changeTimeRange(e) {
    const timeRange = e.currentTarget.dataset.range
    
    if (timeRange === this.data.timeRange) {
      return // 避免重复切换
    }
    
    this.setData({ 
      timeRange,
      showDayView: timeRange === 'day',
      showWeekView: timeRange === 'week',
      showMonthView: timeRange === 'month'
    }, () => {
      this.fetchData()
    })
  },

  showQualityInfo() {
    wx.showModal({
      title: '血压质量评价标准',
      content: '正常范围：收缩压90-139mmHg，舒张压60-89mmHg\n偏高：收缩压≥140mmHg或舒张压≥90mmHg\n偏低：收缩压<90mmHg或舒张压<60mmHg',
      showCancel: false
    })
  },

  onLearnMoreTap() {
    wx.navigateTo({
      url: '../bloodpressure/knowledge'
    })
  },

  showActionSheet() {
    wx.showActionSheet({
      itemList: ['数据记录', '手动添加', '血压设置'],
      itemColor: '#333333',
      success: (res) => {
        switch (res.tapIndex) {
          case 0: // 数据记录
            wx.navigateTo({
              url: '/pages/history/history?type=bloodPressure',
              events: {
                // 数据变更事件
                dataChanged: (data) => {
                  console.log('收到历史页面数据变更事件:', data);
                  this.forceRefresh();
                }
              },
              success: (res) => {
                res.eventChannel.on('dataChanged', (data) => {
                  console.log('通过事件通道收到历史页面数据变更:', data);
                  this.forceRefresh();
                });
              }
            });
            break;
          case 1: // 手动添加
            wx.navigateTo({
              url: '/pages/record/record?type=bloodPressure',
              events: {
                recordAdded: (data) => {
                  console.log('收到记录添加事件:', data);
                  this.forceRefresh();
                }
              },
              success: (res) => {
                res.eventChannel.on('recordAdded', (data) => {
                  console.log('通过事件通道收到记录添加:', data);
                  this.forceRefresh();
                });
              }
            });
            break;
          case 2: // 血压设置
            wx.navigateTo({
              url: '/pages/settings/bloodPressureSettings'
            });
            break;
        }
      }
    });
  },
  
  // 强制刷新数据
  forceRefresh() {
    console.log('强制刷新血压数据');
    this.clearAllCache();
    this.setData({ 
      needRefresh: true,
      lastFetchTime: null 
    });
    this.fetchData();
  },
  
  // 清除所有缓存
  clearAllCache() {
    console.log('清除所有血压数据缓存');
    this.setData({
      cachedData: {
        day: {},
        week: {},
        month: {}
      },
      lastFetchTime: null
    });
  },

  // 原来的clearCache方法修改为处理特定时间范围
  clearCache(timeRange) {
    if (timeRange === 'day') {
      this.setData({
        dayRecords: [],
        needRefresh: true
      });
    } else if (timeRange === 'week') {
      this.setData({
        weekRecords: [],
        needRefresh: true
      });
    } else if (timeRange === 'month') {
      this.setData({
        monthRecords: [],
        needRefresh: true
      });
    }
  },

  onReady: function() {
    // 在页面渲染完成后，初始化图表
    console.log('页面渲染完成，时间范围:', this.data.timeRange);
    // 图表已经由组件自动渲染，不需要手动调用绘图函数
  },

  // 获取血压等级
  getBPLevel(value, type) {
    value = parseInt(value);
    
    if (type === 'systolic') {
      if (value < 90) return 'low';
      if (value < 120) return 'normal';
      if (value < 140) return 'elevated';
      if (value < 180) return 'high';
      return 'crisis';
    } else { // diastolic
      if (value < 60) return 'low';
      if (value < 80) return 'normal';
      if (value < 90) return 'elevated';
      if (value < 120) return 'high';
      return 'crisis';
    }
  },

  // 处理周视图数据 - 显示每一次血压记录而不是每天平均值
  processWeeklyData(records) {
    // 计算本周的第一天（星期日）
    const startDate = this.getStartOfWeek(this.data.selectedDateStr);
    const startDay = startDate.getDate();
    const startMonth = startDate.getMonth();
    const startYear = startDate.getFullYear();
    
    // 按照日期排序记录
    records.sort((a, b) => {
      const dateA = new Date(a.measuredAt || a.timestamp);
      const dateB = new Date(b.measuredAt || b.timestamp);
      return dateA - dateB;
    });
    
    // 提取血压数值和标签
    const systolicData = [];
    const diastolicData = [];
    const xLabels = [];
    
    // 处理每一条记录
    records.forEach(record => {
      const recordDate = new Date(record.measuredAt || record.timestamp);
      // 如果在当前周内
      if (recordDate >= startDate && 
          recordDate < new Date(startYear, startMonth, startDay + 7)) {
        
        systolicData.push(parseInt(record.systolic, 10));
        diastolicData.push(parseInt(record.diastolic, 10));
        
        // 创建标签：周几+时间
        const dayIndex = recordDate.getDay();
        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        const hours = this.formatNumber(recordDate.getHours());
        const minutes = this.formatNumber(recordDate.getMinutes());
        xLabels.push(`${weekdays[dayIndex]} ${hours}:${minutes}`);
      }
    });
    
    console.log('周视图处理后的数据点数量:', systolicData.length);
    
    // 如果没有记录，创建默认标签以显示周框架
    if (systolicData.length === 0) {
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      for (let i = 0; i < 7; i++) {
        xLabels.push(weekdays[i]);
      }
    }
    
    // 计算统计值
    let statistics = {
      average: '--/--',
      max: '--/--',
      min: '--/--',
      totalChange: '--'
    };
    
    if (systolicData.length > 0 && diastolicData.length > 0) {
      const avgSystolic = Math.round(systolicData.reduce((a, b) => a + b, 0) / systolicData.length);
      const avgDiastolic = Math.round(diastolicData.reduce((a, b) => a + b, 0) / diastolicData.length);
      
      const maxSystolic = Math.max(...systolicData);
      const maxDiastolic = Math.max(...diastolicData);
      
      const minSystolic = Math.min(...systolicData);
      const minDiastolic = Math.min(...diastolicData);
      
      // 计算变化 - 比较第一个和最后一个测量值
      let totalChange = '--';
      if (systolicData.length >= 2) {
        totalChange = systolicData[systolicData.length - 1] - systolicData[0];
      }
      
      statistics = {
        average: `${avgSystolic}/${avgDiastolic}`,
        max: `${maxSystolic}/${maxDiastolic}`,
        min: `${minSystolic}/${minDiastolic}`,
        totalChange: totalChange
      };
    }
    
    console.log('处理后的周视图数据:', {
      systolicData,
      diastolicData,
      xLabels,
      statistics
    });
    
    return {
      systolicData,
      diastolicData,
      xLabels,
      statistics
    };
  },

  getBloodPressureRecords(startDate, endDate) {
    return new Promise((resolve, reject) => {
      const app = getApp();
      api.getBloodPressureRecordsByDate({
        userId: app.globalData.userId,
        startDate,
        endDate
      })
      .then(res => {
        if (res.data && res.data.records) {
          resolve(res.data.records);
      } else {
          resolve([]);
        }
      })
      .catch(err => {
        console.error('获取血压记录失败:', err);
        reject(err);
      });
    });
  },

  getMonthInfo(dateStr) {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const monthYear = `${year}-${this.formatNumber(month)}`;
    const daysInMonth = new Date(year, month, 0).getDate();
    
    return {
      monthYear,
      daysInMonth
    };
  },
  
  // 格式化数字，个位数前补0
  formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },
  
  // 获取一周的开始日期（星期日）
  getStartOfWeek(dateStr) {
    const date = new Date(dateStr);
    const day = date.getDay(); // 0是周日，1是周一，以此类推
    date.setDate(date.getDate() - day); // 回退到本周日
    return date;
  },
})